﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Xml;
using DotNet.Mvc;
using XNWebService;
using DotNet.Configuration;

namespace XNWebAPI.Controllers
{
    public class BusController : JsonController
    {
        /// <summary>
        /// 根据公交上下行线路标识获取线路走向数据
        /// </summary>
        /// <param name="segmentId">公交上下行线路标识</param>
        public ActionResult GetBusShapBySegmentId(string segmentId)
        {
            var data = ApiService.GetXLJW(segmentId);
            return Json(data);
        }

        /// <summary>
        /// 根据公交上下行线路标识获取公交站线路途经站点数据
        /// </summary>
        /// <param name="segmentId">公交上下行线路标识</param>
        public ActionResult GetStationBySegmetId(string segmentId)
        {
            var data = ApiService.GetWay(segmentId);
            return Json(data);
        }

        /// <summary>
        /// 通过线路ID查询线路信息
        /// </summary>
        /// <param name="routeId">线路ID</param>
        public ActionResult GetBusLineById(string routeId)
        {
            var data = ApiService.GetLine(routeId);
            return Json(data);
        }

        /// <summary>
        /// 通过公交站点名称模糊查询站点信息
        /// </summary>
        /// <param name="sname">站点名称</param>
        /// <param name="isFuzMatching">true 模糊匹配,false 精确查找</param>
        public ActionResult GetStationByName(string sname, bool isFuzMatching = true)
        {
            var data = ApiService.GetStation(sname, isFuzMatching);
            return Json(data);
        }

        /// <summary>
        /// 通过公交站点名称模糊查询站点信息（同名站点合并）
        /// </summary>
        /// <param name="sname">站点名称</param>
        /// <param name="isFuzMatching">true 模糊匹配,false 精确查找</param>
        public ActionResult GetMergeStationByName(string sname, bool isFuzMatching = true)
        {
            var data = ApiService.GetMergeStation(sname, isFuzMatching);
            return Json(data);
        }

        /// <summary>
        /// 通过公交站点Id查询站点信息
        /// </summary>
        /// <param name="sid">站点Id</param>
        public ActionResult GetStationById(string sid)
        {
            var data = ApiService.GetStationById(sid);
            return Json(data);
        }


        /// <summary>
        /// 通过线路名称查询对应的线路号信息
        /// </summary>
        /// <param name="buslinename">线路名称</param>
        public ActionResult GetBusLineByName(string buslinename)
        {
            var data = ApiService.GetBusLineByName(buslinename);
            return Json(data);
        }

        /// <summary>
        /// 根据公交上下行线路标识获取公交单程线路中的首末班时间和（起步）票价
        /// </summary>
        /// <param name="segmentId">公交上下行线路标识</param>
        public ActionResult GetBusLineInfoBySegmentId(string segmentId)
        {
            var data = ApiService.GetBusLineInfoBySegmentId(segmentId);
            return Json(data);
        }

        /// <summary>
        /// 通过线路标识查询实时公交信息
        /// </summary>
        /// <param name="routeid">线路ID</param>
        public ActionResult GetRealBusLine(string routeid)
        {
            var data = ApiService.GetRealBusLine(routeid);
            return Json(data);
        }

        /// <summary>
        /// 根据坐标和公交线路标识(上下行标识)获取该线路距离自己最近的站点信息
        /// </summary>
        /// <param name="segmentId">公交上下行线路标识</param>
        /// <param name="longitude">经度</param>
        /// <param name="latitude">纬度</param>
        public ActionResult GetNearBusStationByCordLineId(string segmentId, string longitude, string latitude)
        {
            var data = ApiService.GetNearBusStationByCordLineId(segmentId, longitude, latitude);
            return Json(data);
        }

        /// <summary>
        /// 根据坐标获取一定距离内停车场的信息以距离查询坐标的远近进行排序
        /// </summary>
        /// <param name="distance">距离(米)</param>
        /// <param name="longitude">经度</param>
        /// <param name="latitude">纬度</param>
        public ActionResult GetNearparkingByDistance(string distance, string longitude, string latitude)
        {
            var data = ApiService.GetNearparkingByDistance(distance, longitude, latitude);
            return Json(data);
        }

        /// <summary>
        /// 返回json格式的换乘结果
        /// </summary>
        /// <param name="strategy">结果排序规则</param>
        /// <param name="orig">起点为经纬度</param>
        /// <param name="dest">终点为经纬度</param>
        /// <returns></returns>
        public JsonResult GetBusBigCity(string strategy, string orig, string dest)
        {
            string sort = "";
            if (strategy == "1")
            {
                sort = "subway";
            }
            else if (strategy == "2")
            {
                sort = "nonstop";
            }
            else if (strategy == "3")
            {
                sort = "shortWalk";
            }

            var ht = GetBusBigCityXml(sort, orig, dest);

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(ht);
            string json = Newtonsoft.Json.JsonConvert.SerializeXmlNode(doc);

            return Json(json, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 返回XML换乘结果
        /// </summary>
        /// <param name="sort">结果排序规则[subway,nonstop,shortWalk]</param>
        /// <param name="orig">起点为经纬度</param>
        /// <param name="dest">终点为经纬度</param>
        /// <returns></returns>
        public string GetBusBigCityXml(string sort, string orig, string dest)
        {
            //var mUrl = "http://125.72.62.19:8884/bus/getBusBigCity.jsp?&city=%E8%A5%BF%E5%AE%81%E5%B8%82&orig=" + orig + "&dest=" + dest + "&width=1088&height=1024&sort=" + sort + "&customer=2&all=1&walkShow=1&merge=false&encode=utf-8";
            var mUrl = ConfigManager.GetAppValue("BusTransferUrl");
            mUrl = mUrl + "?&city=%E8%A5%BF%E5%AE%81%E5%B8%82&orig=" + orig + "&dest=" + dest + "&width=1088&height=1024&sort=" + sort + "&customer=2&all=1&walkShow=1&merge=false&encode=utf-8";
            return HttpRequestGet(mUrl);
        }

        /// <summary>
        /// HttpWebRequest对象
        /// </summary>
        /// <returns></returns>
        private static string HttpRequestGet(string webApiUrl)
        {
            string retString = "";
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(webApiUrl);   //POST请求的地址

                request.KeepAlive = true;
                //上面的http头看情况而定，但是下面俩必须加[比较重要]  
                request.ContentType = "application/json";
                request.Method = "GET";
                Encoding encoding = Encoding.UTF8;//根据网站的编码自定义  

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream responseStream = response.GetResponseStream();
                //如果http头中接受gzip的话，这里就要判断是否为有压缩，有的话，直接解压缩即可  
                if (response.Headers["Content-Encoding"] != null && response.Headers["Content-Encoding"].ToLower().Contains("gzip"))
                {
                    responseStream = new GZipStream(responseStream, CompressionMode.Decompress);
                }
                StreamReader streamReader = new StreamReader(responseStream, encoding);
                retString = streamReader.ReadToEnd();

                streamReader.Close();
                responseStream.Close();
            }
            catch
            {
                retString = "{\"StatusCode\":-1,\"TotalCount\":0}";
            }

            return retString;
        }

    }
}